package com.gxa.k12.course.exception;


import com.gxa.k12.common.exception.BizCodeEnum;
import com.gxa.k12.common.exception.BusinessException;
import com.gxa.k12.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：Win
 * @Date: 2021/7/6 15:25
 * @Description:
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.gxa")
public class GlobalException {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationException(MethodArgumentNotValidException e) {
        log.error("数据校验出错{}，异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, Object> map = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            /*产生错误的字段名*/
            String field = item.getField();
            /*错误信息*/
            String message = item.getDefaultMessage();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALIDA_EXCEPTION.getCode(), BizCodeEnum.VALIDA_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(BusinessException.class)
    public R handleBusinessException(BusinessException e) {
        log.error("产生了异常：{}", e.getMessage());
        return R.error(BizCodeEnum.BUSINESS_EXCEPTION.getCode(), e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    public R handleGlobalException(Throwable t) {
        log.error("产生了异常：{}", t.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
